<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据查询</el-breadcrumb-item>
    </el-breadcrumb>
    <hr/>
    <div class="app-container">
      <el-form ref="queryForm" :model="queryParams" :rules="queryRules" size="small" :inline="true" label-width="120px">
        <el-form-item label="学校名称" prop="zxmc">
          <el-input
              v-model="queryParams.zxmc"
              placeholder="请输入学校名称"
              clearable
          />
        </el-form-item>
        <el-form-item label="准考证号" prop="zkh">
          <el-input
              v-model="queryParams.zkh"
              placeholder="请输入准考证号"
              clearable
          />
        </el-form-item>
        <el-form-item label="建档号" prop="jdh">
          <el-input
              v-model="queryParams.jdh"
              placeholder="请输入建档号"
              clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="sfzh">
          <el-input
              v-model="queryParams.sfzh"
              placeholder="请输入身份证号"
              clearable
          />
        </el-form-item>
        <el-form-item label="项目" prop="xcxm">
          <el-select v-model="queryParams.xcxm">
            <el-option label="跳绳" value="跳绳"/>
            <el-option label="排球" value="排球"/>
          </el-select>
        </el-form-item>
        <el-form-item label="定时时间(毫秒)" prop="syncIntervalTime">
          <el-input type="Number" v-model="syncIntervalTime"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="info" icon="el-icon-refresh" size="mini" @click="handUpload1">1、同步平台成绩至本地
          </el-button>
          <el-button type="success" icon="el-icon-refresh" size="mini" @click="handUpload2">2、同步本地成绩至第三方
          </el-button>
          <el-button
              :type="syncButtonType"
              round
              :icon="syncButtonIcon"
              size="mini"
              @click="toggleAutoSync"
              :loading="syncLoading"
          >
            {{ syncButtonText }}
          </el-button>
          <el-button type="warning" round icon="el-icon-refresh" size="mini" @click="handExamCloudStudentsList">
            手动同步【手动执行1和2逻辑】一次
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" border :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校名称" align="center" prop="zxmc"/>
      <el-table-column label="准考证号" align="center" prop="zkh"/>
      <el-table-column label="建档号" align="center" prop="jdh"/>
      <el-table-column label="身份证号" align="center" prop="sfzh"/>
      <el-table-column label="班级代码" align="center" prop="bjdm"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <div v-if="scope.row.gender===0">男</div>
          <div v-if="scope.row.gender===1">女</div>
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center" prop="className"/>
      <el-table-column label="选测项目1" align="center" prop="xctyxm1"/>
      <el-table-column label="选测项目1成绩" align="center" prop="xctyxm1Result"/>
      <el-table-column label="选测项目2" align="center" prop="xctyxm2"/>
      <el-table-column label="选测项目2成绩" align="center" prop="xctyxm2Result"/>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        :pageSizes=[30,50,100,150,200,250,300]
        :limit=50
        @pagination="getList"
        style="float: right"
    />
  </div>
</template>

<script>
import {getExamCloudStudentsList, syncCloudResultLocal, syncLocalResultThird} from "@/api/students";
import Pagination from "@/components/Pagination/index.vue";

export default {
  name: 'Home',
  components: {Pagination},
  data() {
    return {
      loading: true,
      queryParams: {
        zxmc: null,
        zkh: null,
        jdh: null,
        sfzh: null,
        xcxm: '跳绳',
        pageNum: 1,
        pageSize: 50
      },
      studentList: [],
      // 总条数
      total: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      studentCodes: [],
      type: this.$route.query.type,
      queryRules: {
        xcxm: [
          {required: true, message: "请选择项目", trigger: "change"}
        ],
      },

      isAutoSyncing: false, // 是否正在自动同步
      syncInterval: null,   // 定时器ID
      syncLoading: false,  // 按钮加载状态
      syncIntervalTime: 300000, // 300秒同步一次
      number1: 0
    };
  },
  computed: {
    syncButtonType() {
      return this.isAutoSyncing ? 'danger' : 'primary'
    },
    syncButtonIcon() {
      return this.isAutoSyncing ? 'el-icon-close' : 'el-icon-refresh'
    },
    syncButtonText() {
      return this.isAutoSyncing ? '停止自动同步' : '自动同步【自动执行1和2逻辑】'
    }
  },
  watch: {
    // 监听路由参数变化
    '$route.query.type': {
      immediate: true, // 立即执行一次
      handler(newType) {
        console.log(newType)
        this.updateXcxm(newType);
        this.getList();
      }
    }
  },
  metaInfo() {
    return {
      title: process.env.VUE_APP_TITLE,
      titleTemplate: '数据查询'
    }
  },
  created() {
    // 正确获取路由参数
    const type = this.$route.query.type || this.type;
    console.log('当前type:', type);
    this.updateXcxm(type)
    this.getList();
  },
  mounted() {
  },
  methods: {
    updateXcxm(type) {
      if ('1' === type) {
        this.queryParams.xcxm = '跳绳';
      } else if ('2' === type) {
        this.queryParams.xcxm = '排球';
      } else {
        this.queryParams.xcxm = '跳绳';
      }
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1; // 搜索时重置页码
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        zxmc: null,
        zkh: null,
        jdh: null,
        sfzh: null,
        xcxm: '跳绳',
        pageNum: 1,
        pageSize: 50
      };
      this.$nextTick(() => {
        this.getList();
      });
      this.resetForm('queryForm')
    },
    // 同步平台成绩至本地
    async handUpload1() {
      await this.$nextTick(); // 等待DOM更新
      // 添加防御性检查
      const form = this.$refs["queryForm"];
      if (!form) {
        console.error('表单引用不存在，请检查ref="queryForm"');
        return;
      }
      const isValid = await form.validate();
      console.log(isValid)
      if (isValid) {
        try {
          this.loading = true
          syncCloudResultLocal(this.queryParams).then(response => {
            if (200 === response.code) {
              this.$message.success(response.msg);
            } else {
              this.$message.warning(response.msg);
            }
            this.handleQuery()
          }).finally(() => {
                this.loading = false
              }
          )
        } catch (error) {
          console.log('验证失败', error);
        }
      } else {
        this.$message.warning('请检查表单输入');
        this.loading = false
      }
    },
    // 同步本地成绩至第三方
    handUpload2() {
      syncLocalResultThird().then(response => {
        console.log(response)
        if (200 === response.code) {
          this.$message.success(response.msg);
        } else {
          this.$message.warning(response.msg);
        }
        this.handleQuery()
      }).finally(() => {
            this.loading = false
          }
      )
    },
    // 切换自动同步状态
    toggleAutoSync() {
      if (this.isAutoSyncing) {
        this.stopAutoSync();
      } else {
        this.startAutoSync();
      }
    },

    // 开始自动同步
    startAutoSync() {
      this.syncLoading = true;
      // 先立即执行一次同步
      this.handExamCloudStudentsList()
          .then(() => {
            // 成功后设置定时器
            this.isAutoSyncing = true;
            this.syncInterval = setInterval(() => {
              this.handExamCloudStudentsList();
            }, this.syncIntervalTime);
          })
          .finally(() => {
            this.syncLoading = false;
          });
    },
    // 停止自动同步
    stopAutoSync() {
      if (this.syncInterval) {
        clearInterval(this.syncInterval);
        this.syncInterval = null;
      }
      this.isAutoSyncing = false;
    },

    // 获取成绩并上传
    async handExamCloudStudentsList() {
      this.number1 = this.number1 + 1
      await this.handUpload1()
      await this.handUpload2()
      console.log(this.number1)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.studentCodes = selection.map(item => item.studentCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 获取云平台未同步的数据
    async getList() {
      await this.$nextTick(); // 等待DOM更新
      // 添加防御性检查
      const form = this.$refs["queryForm"];
      if (!form) {
        console.error('表单引用不存在，请检查ref="queryForm"');
        return;
      }
      const isValid = await form.validate();
      console.log(isValid)
      if (isValid) {
        try {
          this.loading = true
          getExamCloudStudentsList(this.queryParams).then(response => {
            console.log(response)
            console.log(response.data)
            this.studentList = response.data.rows
            this.total = response.data.total
            console.log(this.studentList)
          }).finally(() => {
                this.loading = false
              }
          )
        } catch (error) {
          console.log('验证失败', error);
        }
      } else {
        this.$message.warning('请检查表单输入');
        this.loading = false
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 5px;
}
</style>
